package com.ruoyi.fundmonitor.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.attachment.vo.AttachmentVo;
import com.ruoyi.attachment.domain.Attachment;
import com.ruoyi.attachment.service.IAttachmentService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.MyPageHelper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fundmonitor.dto.ReleaseFund;
import com.ruoyi.fundmonitor.vo.TargetFundVo;
import com.ruoyi.project.infoprojecttarget.domain.InfoProjectTarget;
import com.ruoyi.project.infoprojecttarget.mapper.InfoProjectTargetMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fundmonitor.domain.InfoFundMonitor;
import com.ruoyi.fundmonitor.service.IInfoFundMonitorService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资金监控Controller
 *
 * @author ruoyi
 * @date 2023-03-13
 */
@Api(tags = "资金监控接口")
@RestController
@RequestMapping("/fundonitor/fundmonitor")
public class InfoFundMonitorController extends BaseController {
    @Autowired
    private IInfoFundMonitorService infoFundMonitorService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private InfoProjectTargetMapper targetMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IAttachmentService attachmentService;

    /**
     * 查询资金监控列表
     */
//    @PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoFundMonitor infoFundMonitor) {
        startPage();
        List<InfoFundMonitor> list = infoFundMonitorService.selectInfoFundMonitorList(infoFundMonitor);
        return getDataTable(list);
    }

    /**
     * 导出资金监控列表
     */
    @PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:export')")
    @Log(title = "资金监控", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoFundMonitor infoFundMonitor) {
        List<InfoFundMonitor> list = infoFundMonitorService.selectInfoFundMonitorList(infoFundMonitor);
        ExcelUtil<InfoFundMonitor> util = new ExcelUtil<InfoFundMonitor>(InfoFundMonitor.class);
        util.exportExcel(response, list, "资金监控数据");
    }

    /**
     * 获取资金监控详细信息
     */
    @PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(infoFundMonitorService.selectInfoFundMonitorById(id));
    }

    /**
     * 新增资金监控
     */
    @PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:add')")
    @Log(title = "资金监控", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoFundMonitor infoFundMonitor) {
        return toAjax(infoFundMonitorService.insertInfoFundMonitor(infoFundMonitor));
    }

    /**
     * 修改资金监控
     */
    //@PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:edit')")
    @Log(title = "资金监控", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(InfoFundMonitor infoFundMonitor) {
        return toAjax(infoFundMonitorService.updateInfoFundMonitor(infoFundMonitor));
    }

    /**
     * 删除资金监控
     */
    @PreAuthorize("@ss.hasPermi('fundmonitor:fundmonitor:remove')")
    @Log(title = "资金监控", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(infoFundMonitorService.deleteInfoFundMonitorByIds(ids));
    }

    /**
     * 资金审核列表
     * 如果是填报用户 0 主管 1  财政 2
     * 前端传 projectName
     *
     * @param target
     * @return
     */
    @ApiOperation("资金监控审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectName", value = "项目名称")
    })
    @GetMapping("/releaseList")
    // 项目名称 projectName
    // 监控期间 两个时间段开始和结束
    // 实施单位 workCompany
    public TableDataInfo releaseList(InfoProjectTarget target,int pageNum,int pageSize) {
        Date fundStartTime = target.getFundStartTime();
        Date fundEndTime = target.getFundEndTime();

        //查当前用户角色
        List<TargetFundVo> voList = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKey = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        List<InfoProjectTarget> targets;
        target.setExamineStatus(4);
        if (roleKey.contains("sjc")) {
            if (fundStartTime != null || fundEndTime != null){
                return getTableDataInfo(target, pageNum, pageSize, fundStartTime, fundEndTime, voList,2l);
            }
            //查所有 状态为通过的
            startPage();
            targets = targetMapper.selectInfoProjectTargetList(target);
            extracted(voList, targets, 2l,fundStartTime,fundEndTime);
        } else {
            target.setDepartmentId(SecurityUtils.getDeptId());
            if (fundStartTime != null || fundEndTime != null){
                return getTableDataInfo(target, pageNum, pageSize, fundStartTime, fundEndTime, voList,1l);
            }
            startPage();
            targets = targetMapper.selectInfoProjectTargetList(target);
            extracted(voList, targets, 1l,fundStartTime,fundEndTime);
        }
        TableDataInfo dataTable = getDataTable(targets);
        dataTable.setRows(voList);
        return dataTable;
    }

    private TableDataInfo getTableDataInfo(InfoProjectTarget target, int pageNum, int pageSize, Date fundStartTime, Date fundEndTime, List<TargetFundVo> voList,Long isWho) {
        List<InfoProjectTarget> targets;
        targets = targetMapper.selectInfoProjectTargetList(target);
        extracted(voList, targets, isWho, fundStartTime, fundEndTime);
        List<TargetFundVo> collect = voList.stream().filter(x -> x.getInfoFundMonitors().size() != 0).collect(Collectors.toList());
        PageInfo pageInfo = MyPageHelper.pageHelpList(collect, pageNum, pageSize);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getList());
        return tableDataInfo;
    }

    /**
     * 公共封装数据
     *
     * @param voList
     * @param targets
     * @param isWho
     */
    private void extracted(List<TargetFundVo> voList, List<InfoProjectTarget> targets, Long isWho,Date fundStartTime,Date fundEndTime) {
        for (InfoProjectTarget infoProjectTarget : targets) {
            TargetFundVo targetFundVo = new TargetFundVo();
            targetFundVo.setInfoProjectTarget(infoProjectTarget);
            InfoFundMonitor infoFundMonitor = new InfoFundMonitor();
            infoFundMonitor.setProjectTargetId(infoProjectTarget.getId());
            infoFundMonitor.setFundStartTime(fundStartTime);
            infoFundMonitor.setFundEndTime(fundEndTime);
            List<InfoFundMonitor> monitors = infoFundMonitorService.selectInfoFundMonitorListByTargetId(infoFundMonitor);
            if (monitors.size() >= 4){
                targetFundVo.setFundSize(4);
            }else {
                targetFundVo.setFundSize(0);
            }
            targetFundVo.setInfoFundMonitors(monitors);
            targetFundVo.setIsWho(isWho);
            voList.add(targetFundVo);
        }
    }

    /**
     * 资金下达 多次下达
     * 前端传 projectTargetId 和 monitorDration  remark
     *
     * @param infoFundMonitor
     * @return
     */
    @ApiOperation("/资金监控下达接口")
    @PostMapping("/releaseFund")
    public AjaxResult releaseFund(@RequestBody InfoFundMonitor infoFundMonitor) {
        return AjaxResult.success(infoFundMonitorService.insertInfoFundMonitor(infoFundMonitor));
    }

    /**
     * 填报列表查询
     * 前端传   项目名称
     *
     * @param infoFundMonitor
     * @return
     */
    @ApiOperation("资金监控填报列表接口")
    @GetMapping("/fillList")
    public TableDataInfo fillList(InfoFundMonitor infoFundMonitor) {
        //根据实施单位id查询当前用户资金
        Long deptId = SecurityUtils.getDeptId();
        infoFundMonitor.setImplementationId(deptId);
        startPage();
        List<InfoFundMonitor> infoFundMonitors = infoFundMonitorService.selectInfoFundMonitorList(infoFundMonitor);
        return getDataTable(infoFundMonitors);
    }

    /**
     * 资金详情
     * 前端传资金监控id
     *
     * @return
     */
    @ApiOperation("资金详情接口")
    @GetMapping("/fundDetail/{id}")
    public AjaxResult fundDetail(@PathVariable("id") Long id) {
        InfoFundMonitor infoFundMonitor = infoFundMonitorService.selectInfoFundMonitorById(id);
        infoFundMonitor.setDepartmentName(sysDeptMapper.selectDeptById(infoFundMonitor.getDepartmentId()).getDeptName());
        infoFundMonitor.setImplementationName(sysDeptMapper.selectDeptById(infoFundMonitor.getImplementationId()).getDeptName());
        DecimalFormat df =  new DecimalFormat("0%");
        String s = df.format(Double.valueOf(infoFundMonitor.getExecuteRate()));
        infoFundMonitor.setExecuteRate(s);
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        List<String> collect = sysUser.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        if (collect.contains("sjc")){
            infoFundMonitor.setTag(2);
        }
        if (collect.contains("common")){
            infoFundMonitor.setTag(1);
        }
        return AjaxResult.success(infoFundMonitor);
    }

    /**
     * 提交审核接口  1待提交，2主管审核，3财政审核中，4通过 5退回
     * 前端传fundStatus 和 id
     *
     * @return
     */
    @ApiOperation("/资金监控提交&审核接口")
    @PostMapping("/examineFund")
    public AjaxResult examineFund(@RequestBody InfoFundMonitor infoFundMonitor) {
        Long fundStatus = infoFundMonitor.getFundStatus();
        if (fundStatus == 2l) {
            //提交
            int i = infoFundMonitorService.updateInfoFundMonitor(infoFundMonitor);
            return AjaxResult.success("提交成功！");
        }
        if (fundStatus == 3l) {
            //审核
            int i = infoFundMonitorService.updateInfoFundMonitor(infoFundMonitor);
            return AjaxResult.success("主管审核通过！");
        }
        if (fundStatus == 4l) {
            //审核
            int i = infoFundMonitorService.updateInfoFundMonitor(infoFundMonitor);
            return AjaxResult.success("财政审核通过！");
        }
        if (fundStatus == 5l) {
            //退回  清除原来填报的数据以及上传的附件
            infoFundMonitor.setArriveFund("0.0000");
            infoFundMonitor.setExecuteFund("0.0000");
            infoFundMonitor.setExecuteRate("0.0000");
            //删除附件
            Attachment attachment = new Attachment();
            attachment.setAttachmentType("1");
            attachment.setInfoId(infoFundMonitor.getId().toString());
            attachment.setTableName("info_fund_monitor");
            List<Attachment> attachments = attachmentService.selectAttachmentList(attachment);
            if (attachments.size() != 0) {
                for (Attachment attachment1 : attachments) {
                    attachmentService.deleteAttachmentByAttachmentId(attachment1.getAttachmentId());
                    attachmentService.deleteServerFile(attachment1.getAttachmentUrl());
                }
            }
            infoFundMonitorService.updateInfoFundMonitorByStatus(infoFundMonitor);
            return AjaxResult.success("退回成功！");
        }
        return AjaxResult.error();
    }

    /**
     * 上传附件
     *
     * @return
     */
    @ApiOperation("/上传附件接口")
    @PostMapping("/uploadMuchFiles")
    public AjaxResult uploadMuchFiles(@RequestBody Attachment attachment) {
        return toAjax(infoFundMonitorService.uploadMuchFiles(attachment, 1));
    }

    /**
     * 删除真实文件以及库中文件
     *
     * @param
     * @return
     */
    @ApiOperation("删除文件")
    @PostMapping("/deleteFile")
    public AjaxResult deleteFile(@RequestBody Attachment attachment) {
        //Attachment attachment = attachmentService.selectAttachmentByAttachmentId(id);
        //
        if (attachment.getAttachmentId() == null) {
            attachmentService.deleteServerFile(attachment.getAttachmentUrl());
            return AjaxResult.success();
        }else {
            attachmentService.deleteServerFile(attachment.getAttachmentUrl());
            int i = attachmentService.deleteAttachmentByAttachmentId(attachment.getAttachmentId());
            return toAjax(i);
        }
    }

    @ApiOperation("撤回监控")
    @DeleteMapping("/recallFund/{id}")
    public AjaxResult recallFund(@PathVariable("id") Long id) {
        InfoFundMonitor infoFundMonitor = infoFundMonitorService.selectInfoFundMonitorById(id);
        if (1 == infoFundMonitor.getFundStatus()) {
            int i = infoFundMonitorService.deleteInfoFundMonitorById(id);
            if (i == 1) {
                return AjaxResult.success("撤回成功！");
            }
            return AjaxResult.error("撤回失败！");
        }
        return AjaxResult.error("只能撤回状态为待提交的监控！");
    }

    /**
     * 附件上传  多文件  前端传  业务id  文件初始名称   url
     *
     * @param attachmentVo
     * @return
     */
    @RequestMapping(value = "/batchInsert", method = RequestMethod.POST)
    public AjaxResult batchInsert(@RequestBody AttachmentVo attachmentVo) {
        AjaxResult ajaxResult = toAjax(infoFundMonitorService.batchInsert(attachmentVo));
        return ajaxResult;
    }

    /**
     * 查询附件
     *
     * @param id
     * @return
     */
    @GetMapping("/selectAttachment/{id}")
    public AjaxResult selectAttachment(@PathVariable("id") Long id) {
        Attachment attachment = new Attachment();
        attachment.setAttachmentType("1");
        attachment.setInfoId(id.toString());
        attachment.setTableName("info_fund_monitor");
        List<Attachment> attachments = attachmentService.selectAttachmentList(attachment);
        return AjaxResult.success(attachments);
    }

    /**
     * 批量下达
     * @param releaseFund
     * @return
     */
    @PostMapping("/releaseFundMultiple")
    public AjaxResult releaseFundMultiple(@RequestBody ReleaseFund releaseFund){
        return infoFundMonitorService.releaseFundMultiple(releaseFund);
    }


}
